/*创建一个长度为3的列表,并对其进行赋值,并打印*/
/*hello.c*/
#include <stdio.h>
#include "python3.5m/Python.h"
int main(int argc, char *argv[]) {
int i=0;
long value;
Py_Initialize();
PyObject *t, *item;
t = PyList_New(3);
PyList_SetItem(t, 0, PyLong_FromLong(1L));
PyList_SetItem(t, 1, PyLong_FromLong(2L));
PyList_SetItem(t, 2, PyLong_FromLong(3L));
for(i=0; i<3;i++) {
item = PyList_GetItem(t, i);
value = PyLong_AsLong(item);
printf("%ld\n", value);
}
Py_Finalize();
return 0;
}
void Py_Initialize()//初始化python解析器,必须在调用Python/C API之前调用
PyObject* PyList_New(Py_ssize_t len)//创建一个长度为len的列表,Return:List Reference OR NULL(创建失败)
/*设置list索引为index的值为item,Return: 0 OR -1*/
int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)
/*获取list索引为index的值,Return: Borrowed reference OR NULL and set an IndexError exception.*/
PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index)
/*返回C类型的变量*/
long PyLong_AsLong(PyObject *obj)
/*释放资源*/
void Py_Finalize()
/*编译运行,ubuntu 16.04,gcc5.4.0,python3.5*/
/*-L 指定库的路径,-l 指定需连接的库名
如果文件为libpython3.5.so,刚库名为python3.5*/
gcc hello.c -L/usr/lib/python3.5/config-3.5m-x86_64-linux-gnu -lpython3.5
out:
1
2
3
若/usr/include/python3.5m下无Python.h文件,请RefPython.h
Ref: 1.官方文档